# apps/monitoring/views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework import status
from django.http import JsonResponse
from .models import SensorReading

from .models import SensorReading, ActionLog
from .serializers import SensorReadingSerializer, ActionLogSerializer

import random, decimal
from django.utils import timezone
from apps.rooms.models import Room
from .utils import log_action
from django.views.generic import TemplateView

MAX_ROWS = 300  # 前端一次最多取多少条

class SensorReadingList(APIView):
    permission_classes = [AllowAny]
    def get(self, request):
        room_id = request.query_params.get('room_id')
        qs = SensorReading.objects.select_related('room')
        if room_id: qs = qs.filter(room__room_id=room_id)
        qs = qs.order_by('-recorded_at')[:MAX_ROWS]
        return Response(SensorReadingSerializer(qs, many=True).data)

class ActionLogList(APIView):
    permission_classes = [AllowAny]
    def get(self, request):
        qs = ActionLog.objects.select_related('user','device','device__room') \
                              .order_by('-timestamp')[:MAX_ROWS]
        return Response(ActionLogSerializer(qs, many=True).data)

class UnifiedMessageList(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        readings = SensorReadingList().get(request).data
        logs     = ActionLogList().get(request).data

        for r in readings:
            r.update({
                "message_type": "reading",
                "created_at"  : r["recorded_at"]          # ✅ 保留 recorded_at
            })

        for l in logs:
            l.update({
                "message_type": "log",
                "created_at"  : l["timestamp"]             # ✅ 复制，不 pop
            })
            # 绝对不要  l.pop('timestamp')

        merged = sorted(readings + logs,
                        key=lambda x: x["created_at"],
                        reverse=True)[:300]
        return Response(merged, status=200)

class CollectReading(APIView):
    """POST /sensor_readings/collect/?room_id=1  —— 采集一条随机读数"""
    permission_classes = [AllowAny]

    def post(self, request):
        room_id = request.query_params.get('room_id')
        try:
            room = Room.objects.get(room_id=room_id)
        except Room.DoesNotExist:
            return Response({'detail': 'Room not found'}, status=404)

        temp = decimal.Decimal(random.uniform(18, 60)).quantize(decimal.Decimal('0.01'))
        hum  = decimal.Decimal(random.uniform(30, 95)).quantize(decimal.Decimal('0.01'))
        sr = SensorReading.objects.create(room=room,
                                          temperature=temp,
                                          humidity=hum,
                                          recorded_at=timezone.now())
        log_action(action_type='手动采集',
                   old_value=None,
                   new_value=f"{room.name}:{temp}℃/{hum}%")
        return Response({'message': '采集成功'}, status=201)


class MessagePageView(TemplateView):
    template_name = "messages.html"

def latest_sensor_readings(request):
    # 获取每个房间的最新读数
    latest_readings = []
    rooms = Room.objects.all()
    
    for room in rooms:
        # 获取该房间的最新读数
        reading = SensorReading.objects.filter(room=room).order_by('-recorded_at').first()
        if reading:
            latest_readings.append({
                'reading_id': reading.reading_id,
                'temperature': float(reading.temperature),
                'humidity': float(reading.humidity),
                'recorded_at': reading.recorded_at.isoformat(),
                'room_id': room.room_id
            })
    
    return JsonResponse(latest_readings, safe=False)